<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>发表评论实例</title>
    <script src="../lib/vue-2.4.0.js"></script>
    <link rel="stylesheet" href="../lib/bootstrap-3.3.7.css">
</head>
<body>
<div id="app">
    <cmt-box v-on:loadData="loadComments"></cmt-box>

    <ul class="list-group" style="padding: 24px">
        <li class="list-group-item" v-for="item in list" :key="item.id">
            <span class="badge">评论人：{{ item.user }}</span>
            {{ item.content }}
        </li>
    </ul>
</div>

<template id="temp">
    <div style="padding: 24px">
        <div class="form-group">
            <label>评论人：</label>
            <input type="text" class="form-control" v-model="user">
        </div>
        <div class="form-group">
            <label>评论内容：</label>
            <textarea class="form-control" v-model="content"></textarea>
        </div>

        <div class="form-group">
            <input type="button" value="发表评论" class="btn btn-primary" @click="postComment">
        </div>
    </div>
</template>

<script>

    let commentBox = {
        template: '#temp',
        data() {
            return {
                user: '',
                content: '',
            }
        },
        methods: {
            postComment() {

                var comment = {id: Date.now(), user: this.user, content: this.content}

                var list = JSON.parse(localStorage.getItem('cmts') || '[]')
                list.unshift(comment)

                localStorage.setItem('cmts', JSON.stringify(list))

                this.user = this.content = ''

                this.$emit('loaddata')

            },
        },
    }
    let vm = new Vue({
        el: '#app',
        data: {
            list: [
                {id: Date.now(), user: '李白', content: '天生我材必有用'},
            ]
        },
        created() {
            this.loadComments()
        },
        methods: {
            loadComments() {//从本地 localStorage 中加载评论列表
                var list = JSON.parse(localStorage.getItem('cmts') || '[]')
                console.log(list)
                // for (let i in list) {
                //     this.list.unshift(list[i]);
                // }
                this.list = list
            }
        },
        components: {
            'cmt-box': commentBox
        },
    })
</script>
</body>
</html>
